package com.delivery.deliverysystem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.delivery.deliverysystem.common.FieldDisplay;
import com.delivery.deliverysystem.dao.DefaultNameMapper;
import com.delivery.deliverysystem.dao.UserMapper;
import com.delivery.deliverysystem.exception.RException;
import com.delivery.deliverysystem.pojo.DAO.CompanyDTO;
import com.delivery.deliverysystem.pojo.DO.Company;
import com.delivery.deliverysystem.pojo.DO.DefaultName;
import com.delivery.deliverysystem.pojo.DO.User;
import com.delivery.deliverysystem.service.CommonService;
import com.delivery.deliverysystem.service.CompanyService;
import com.delivery.deliverysystem.dao.CompanyMapper;
import com.delivery.deliverysystem.util.RegistrationCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.delivery.deliverysystem.util.PasswordUtil.sha1Encode;

/**
* @author Administrator
* @description 针对表【company(公司资料表)】的数据库操作Service实现
* @createDate 2025-01-13 15:37:40
*/
@Service
@Slf4j
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company>
    implements CompanyService{

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    DefaultNameMapper defaultNameMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    CommonService commonService;

    @Value("${upload.path}")
    private String uploadPath;

    @Override
    public boolean createCompany(CompanyDTO companyDTO) throws RException {
        if(companyDTO ==null) return false;
        String registrationCode = companyDTO.getRegistrationCode();
        String encryptCode = null;
        //将用户获得的注册码加密与数据库中的注册码进行比较
        if(RegistrationCodeUtil.validateCode(registrationCode)){
            encryptCode = RegistrationCodeUtil.encryptCode(registrationCode);
        }
        Company company = companyMapper.selectOne(new QueryWrapper<Company>().eq("registration_code", encryptCode));
        if(company==null) throw new RException("注册码有误",500);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCompany(String logoPath,CompanyDTO companyDTO) throws Exception{
        Integer companyId = companyDTO.getCompanyId();
        if(companyDTO ==null || companyId==null) return false;
        Company company = companyMapper.selectById(companyId);
        if(company==null) throw new RException("公司不存在",500);
        //更新可修改的字段
        if(companyDTO.getCompanyName()!=null){
            company.setFullName(companyDTO.getCompanyName());
        }
        if(companyDTO.getCompanyShort()!=null){
            company.setAbbreviation(companyDTO.getCompanyShort());
        }
        if(companyDTO.getEnglishName()!=null){
            company.setEnglishName(companyDTO.getEnglishName());
        }
        if(companyDTO.getAddress()!=null){
            company.setAddress(companyDTO.getAddress());
        }
        if(companyDTO.getHomePage()!=null){
            company.setHomepage(companyDTO.getHomePage());
        }
        if(companyDTO.getPhoneNumber()!=null){
            company.setPhone(companyDTO.getPhoneNumber());
        }
        if(companyDTO.getFax()!=null){
            company.setCompanyFax(companyDTO.getFax());
        }
        if(companyDTO.getEmail()!=null){
            company.setEmail(companyDTO.getEmail());
        }
        if(companyDTO.getDepositBank()!=null){
            company.setBank(companyDTO.getDepositBank());
        }
        if(companyDTO.getBankAccount()!=null){
            company.setBankAccount(companyDTO.getBankAccount());
        }
        if(companyDTO.getTaxNumber()!=null){
            company.setTaxNum(companyDTO.getTaxNumber());
        }
        if(logoPath!=null){
            //删除原来的logo文件
            String companyLogoPath = company.getCompanyLogo();
            if(companyLogoPath!=null) {
                //如果文件存在则删除文件，否则直接set新的图片地址
                File existLogo = new File(uploadPath+companyLogoPath);
                if(existLogo.exists()){
                    commonService.deleteFile(companyLogoPath);
                }
            }
            company.setCompanyLogo(logoPath);
        }
        if(companyDTO.getCompanyQrCode()!=null){
            company.setCompanyQrCode(companyDTO.getCompanyQrCode());
        }
        return companyMapper.updateById(company)>0;
    }

    @Override
    public Company getCompanyById(Integer companyId) {
        if(companyId==null) return null;
        return companyMapper.selectById(companyId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> generateCode(String filePath, String companyName) throws RException {
        Company companyExist = companyMapper.selectOne(new QueryWrapper<Company>().eq("full_name", companyName));
        if(companyExist!=null) throw new RException("公司已经存在",500);
        String code = RegistrationCodeUtil.generateCode(32);
        //验证注册码格式，通过则加密保存
        String encryptCode = null;
        if(RegistrationCodeUtil.validateCode(code)){
            encryptCode = RegistrationCodeUtil.encryptCode(code);
            Company registrationCode = companyMapper.selectOne(new QueryWrapper<Company>().eq("registration_code", encryptCode));
            //判断注册码是否重复(理论上可以生成62^32种注册码，重复的概率还是很小的)
            if(registrationCode!=null) throw new RException("注册码已存在",500);
            Company add = Company.builder()
                    .fullName(companyName)
                    .companyLogo(filePath)
                    .registrationCode(encryptCode)
                    .build();
            if(companyMapper.insert(add)<0) throw new RException("生成注册码失败",500);
        }

        Company company = companyMapper.selectOne(new QueryWrapper<Company>().eq("registration_code", encryptCode));
        //创建系统管理员
        List<DefaultName> defaultNames = defaultNameMapper.selectList(null);
        Map<String,Object> UserDefaultName = new HashMap<>();
        for (DefaultName defaultName:defaultNames){
            String defaultName1 = defaultName.getDefaultName();
            UserDefaultName.put(defaultName1,defaultName1);
        }
        String jsonString = JSONObject.toJSONString(UserDefaultName);
        String userCode = UUID.randomUUID().toString();
        User user = User.builder()
                .userCode("System"+userCode)
                .username("系统管理员")
                .password(sha1Encode("123456"))
                .updateColumn(jsonString)
                .createDeliveryDisplay(FieldDisplay.DELIVERY_DISPLAY)
                .productDisplay(FieldDisplay.PRODUCT_DISPLAY)
                .companyId(company.getCompanyId())
                .build();
        Map<String,String> admin = new HashMap<>();
        admin.put("userCode",user.getUserCode());
        admin.put("username",user.getUsername());
        admin.put("password","123456");
        if(userMapper.insert(user)<=0) throw new RException("系统管理员创建失败",500);
        Map<String,Object> result = new HashMap<>();
        result.put("registrationCode",code);
        result.put("admin",admin);
        return result;
    }


}




